Published 2006-12-22 13:00:00
sessionStorage.setItem("mycache_somedata", JSON_toString(mydata));
... and onloading..
var mydata = new Array();
if (sessionStorage.getItem("mycache_somedata")) {
eval("mydata = " + sessionStorage.getItem("mycache_somedata").value);
}
/**
* Standard JSON encoder.
*/
JSON_toString = function (obj) {
function df(n) {
return n < 10 ? '0' + n : n;
}
var m = {
'\b': '\\b',
'\t': '\\t',
'\n': '\\n',
'\f': '\\f',
'\r': '\\r',
'"' : '\\"',
'\\': '\\\\'
};
switch(typeof obj) {
case 'string':
// fixme - this needs to do better escaping!
var ret = '"';
for(var i = 0;i<obj.length;i++) {
if (m[obj[i]]) {
ret += m[obj[i]];
continue;
}
ret += obj[i];
}
return ret + '"';
case 'boolean':
return String(obj) ;
case 'date':
return '"' + obj.getFullYear() + '-' +
df(obj.getMonth() + 1) + '-' +
df(obj.getDate()) + 'T' +
df(obj.getHours()) + ':' +
df(obj.getMinutes()) + ':' +
df(obj.getSeconds()) + '"';
case 'number':
return isFinite(obj) ? String(obj) : "null";
case 'object':
return JSON_ObjectToString(obj);
case 'array':
return JSON_ArrayToString(obj);
default:
return '';
}
};
function JSON_ObjectToString(obj)
{
var a = ['{'], b;
function p(k, s) {
if (b) {
a.push(',');
}
a.push(JSON_toString(k), ':', s);
b = true;
}
for (var i in obj) {
if (!obj.hasOwnProperty(i)) {
continue;
}
var v = obj[i];
switch (typeof v) {
case 'undefined':
case 'function':
case 'unknown':
break;
case 'object':
if (!v) {
p(i, 'null');
break;
}
default:
p(i, JSON_toString(v));
break;
}
}
//alert('keys = ' + tmps);
a.push('}');
//alert(a.join(''));
return a.join('');
}
function JSON_ArrayToString(obj)
{
var a = ['['], b, l = obj.length;
function p(s) {
if (b) {
a.push(',');
}
a.push(s);
b = true;
}
for (var i = 0; i < l; i += 1) {
var v = this[i];
switch (typeof v) {
case 'undefined':
case 'function':
case 'unknown':
break;
case 'object':
if (!v) {
p("null");
break;
}
default:
p(JSON_toString(v));
}
}
a.push(']');
return a.join('');
}